<?php

class Application_Model_Generalize extends Application_Model_DomainObject {

    protected $_id;
    /**
     * 推广名称
     */
    protected $_name;
    /**
     * 推广标识
     */
    protected $_no;
    /**
     * 推广内容
     */
    protected $_content;
    /**
     * 状态
     */
    protected $_status;
    /**
     * 推广国家
     */
    protected $_cityId;
    /**
     * 创建时间
     */
    protected $_createdTime;
    /**
     * 开始时间
     */
    protected $_startTime;
    /**
     * 结束时间
     */
    protected $_endTime;
    
    /**
     * 默认未开启
     */
    const Status_Default = 0;
    /**
     * 已开启
     */
    const Status_Launch = 1;
    
    
    public static function getFilter($generalizeSearch,$pagesize,$pageindex)
    {
        return self::getDao()->queryPage($generalizeSearch->getSearchFileds(), " id desc ", $pagesize, $pageindex);
    }
    

    public static function getStatusAll()
    {
        return array(
                   self::Status_Default => "未启动"
                ,  self::Status_Launch => "启动"
        );
    }
    
    public function getStatusName()
    {
        $arrStatus = self::getStatusAll();
        return $arrStatus[$this->_status];
    }
    
    public function getCityInfo() {
        return Application_Model_city::load($this->_cityId);
    }
    
    /**
     * 添加活动
     * @param type $name 活动名称
     * @param type $content 活动内容
     * @param type $type 活动类型
     * @param type $status 活动状态
     * @param type $startTime 活动开始时间
     * @param type $endTime 活动结束时间
     * @param type $giftId 礼物ID
     * @param type $sumNum 发放数量
     */
    public static function addGeneralize($no, $name, $content, $startTime, $endTime, $cityId, $status)
    {
        $generalizeItem = new Application_Model_Generalize();
        $generalizeItem->No = $no;
        $generalizeItem->Name = $name;
        $generalizeItem->Content = $content;
        $generalizeItem->Status = $status;
        $generalizeItem->StartTime = $startTime;
        $generalizeItem->EndTime = $endTime;
        $generalizeItem->CityId = $cityId;
        $generalizeItem->createdTime = date("Y-m-d H:i:s");
        $generalizeItem->save();
        return $generalizeItem->Id;
    }
        
    public function getRuleAll()
    {
        return Application_Model_GeneralizeRule::getRuleByGeneralizeId($this->_id);
    }
    
    public function editGeneralize($no, $name, $content, $startTime, $endTime, $cityId, $status) {
        $this->_no = $no;
        $this->_name = $name;
        $this->_content = $content;
        $this->_status = $status;
        $this->_startTime = $startTime;
        $this->_endTime = $endTime;
        $this->_cityId = $cityId;
        $this->save();
    }
    
    public function editRule($ruleId,$grantType,$giftType,$giftId,$giftNum,$ruleLimit,$ruleNum,$minRule,$maxRule,$generalizeType,$receiveType) {
        $ruleOldItem = $this->getRuleAll();
        foreach ($ruleOldItem as $ruleVal) {
            if(!in_array($ruleVal->Id, $ruleId)) {
                $ruleVal->delete();
            }
        }
        for ($index = 0; $index < count($grantType); $index++) {
            if(($giftNum[$index] > 0 || $giftNum[$index] != "") && $minRule[$index] != "" && $maxRule[$index] != "" && ($ruleNum[$index] > 0 || $ruleNum[$index] != "")) {
                if($ruleId[$index] > 1000) {
                    $ruleItem = Application_Model_GeneralizeRule::load($ruleId[$index]);
                } else {
                    $ruleItem = new Application_Model_GeneralizeRule();
                    $ruleItem->receiveNum = 0;
                }
                $ruleItem->generalizeId = $this->_id;
                $ruleItem->grantType = $grantType[$index];
                $ruleItem->generalizeType = $generalizeType[$index];
                $ruleItem->giftType = $giftType[$index];
                $ruleItem->giftId = $giftId[$index];
                $ruleItem->num = $giftNum[$index];
                $ruleItem->ruleLimit = $ruleLimit[$index];
                $ruleItem->ruleNum = $ruleNum[$index];
                $ruleItem->minRule = $minRule[$index];
                $ruleItem->maxRule = $maxRule[$index];
                $ruleItem->receiveType = $receiveType[$index];
                $ruleItem->save();
            }
        }
        return true;
    }
    
    public function getReceiveUserNum() {
        $receiveItem = Application_Model_GeneralizeReceive::getDistinct($this->_id,"userId");
        return count($receiveItem);
    }
    
    public static function getItemByNo($no) {
        return self::getDao()->queryOne(array("no = " => $no));
    }
    
    public static function getItemByPgetItemByParticipate($receiveId,$receiveType) {
        $participateItem = Application_Model_GeneralizeParticipate::getItemByReceiveIdAndType($receiveId, $receiveType);
        if(!$participateItem) {
            return false;
        }
        return self::getItemByNo($participateItem->activityCode);
    }

    public function getJudgeIfEffective($datetime = null) {
        if($this->_status == Application_Model_Generalize::Status_Default) {
            return true;
        }
        $datetime = $datetime?$datetime:date("Y-m-d H:i:s");
        return $this->judgeIfDate($datetime);
    }

    /**
     * 领取活动礼物
     * @param type $userId 用户ID 
     * @param type $grantType 参与活动的类型
     * @param type $receiveId 参与活动的Id
     * @param type $receiveType 参与活动的类型
     * @return type 0 未知错误 1成功 2已经领取 3礼物领取完了 4时间错误 5ip段已经领取了 6 推广国家错误
     */
    public function receive($userId,$grantType,$receiveId,$receiveType)
    {
        $return = 0;
//        if($this->judgeIfDate()){
//            return 4;
//        }
        if($this->judgeIfCity($userId)) {
            return 6;
        }
        $ruleItem = Application_Model_GeneralizeRule::getRuleByGeneralizeIdGrantType($this->_id,$grantType);
        if(!$ruleItem) {
            return 7;
        }
        $return = $this->useGeneralize($userId,$ruleItem,$grantType,$receiveId,$receiveType);
        return $return;
    }
    /**
     *  判断是否在活动的有效期之内
     * @return boolean false 存在 true 活动还未还是或已经结束
     */
    private function judgeIfDate($datetime)
    {
        if($datetime < $this->_startTime || $datetime >= $this->_endTime){
            return true;
        }
        return false;
    }
    /**
     * 判断用户的国家是否是活动的推广国家
     * @param type $userId 用户Id
     * @return boolean false 是 true 不是
     */
    private function judgeIfCity($userId) {
        if($this->_cityId == 0) {
            return false;
        }
        $userItem = Application_Model_User::load($userId);
        if($userItem->cityId == $userId) {
            return false;
        }
        return true;
    }
    /**
     * 判断是否符合发放礼物的要求
     * @param type $userId 用户Id
     * @param type $ruleItem 活动规则
     * @param type $grantType 参与活动的类型
     * @param type $receiveId 参与活动的Id
     * @return type
     */
    private function useGeneralize($userId,$ruleItem,$grantType,$receiveId,$receiveType) {
        $receiveItem = self::createdReceive($grantType,$receiveId);
        foreach ($ruleItem as $ruleVal) {
            if($ruleVal->generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Service){
                continue;
            }
            if($grantType == Application_Model_GeneralizeRule::Grant_Share) {
                $this->receiveGift($userId,$ruleVal,$receiveId);
                continue;
            }
            if($ruleVal->giftType != Application_Model_GeneralizeRule::GiftType_Discount && $receiveType != $ruleVal->ReceiveType) {
                continue;
            }
            if($ruleVal->ruleLimit == Application_Model_GeneralizeRule::RuleLimit_Num) {
                $count = $this->countReceive($ruleVal, $userId);
                if($count != 0 && $count >= $ruleVal->minRule && $count < $ruleVal->maxRule) {
                    $this->receiveGift($userId,$ruleVal,$receiveId,$count);
                    continue;
                }
            }
            if($ruleVal->ruleLimit == Application_Model_GeneralizeRule::RuleLimit_Sum) {
                if($receiveItem->getMoney() >= $ruleVal->minRule && $receiveItem->getMoney() < $ruleVal->maxRule) {
                    $this->receiveGift($userId,$ruleVal,$receiveId);
                    continue;
                }
            }
        }
        return 1;
    }
    /**
     * 创建参与活动的对象
     * @param type $grantType 参与活动的类型
     * @param type $receiveId 参与活动的Id
     * @return boolean
     */
    public static function createdReceive($grantType,$receiveId) {
        switch ($grantType) {
            case Application_Model_GeneralizeRule::Grant_Way:
                return Application_Model_wayBillItem::load($receiveId);
            case Application_Model_GeneralizeRule::Grant_Order:
                return Application_Model_Order::load($receiveId);
            case Application_Model_GeneralizeRule::Grant_Visiting:
                return Application_Model_VisitingServer::load($receiveId);
            case Application_Model_GeneralizeRule::Grant_Recharge:
                return Application_Model_RechargeBill::load($receiveId);
            case Application_Model_GeneralizeRule::Grant_Share:
                return true;
            default:
                break;
        }
    }
    
    public static function getReceiveUserId($grantType,$receiveItem) {
        switch ($grantType) {
            case Application_Model_GeneralizeRule::Grant_Way:
            case Application_Model_GeneralizeRule::Grant_Order:
            case Application_Model_GeneralizeRule::Grant_Visiting:
            case Application_Model_GeneralizeRule::Grant_Recharge:
                return $receiveItem?$receiveItem->userId:0;
            case Application_Model_GeneralizeRule::Grant_Share:
                return true;
            default:
                break;
        }
    }


    private function countReceive($ruleVal,$userId) {
        switch ($ruleVal->grantType) {
            case Application_Model_GeneralizeRule::Grant_Way:
                $waySearch = new Application_Model_Filter_WayBillSearch();
                $waySearch->userid = $userId;
                $waySearch->starttime = $this->_startTime;
                $waySearch->endtime = $this->_endTime;
                return Application_Model_wayBillItem::countWay($waySearch);
            case Application_Model_GeneralizeRule::Grant_Order:
                $orderSearch = new Application_Model_Filter_OrderSearch();
                $orderSearch->userid = $userId;
                $orderSearch->seltime = "paidTime";
                $orderSearch->starttime = $this->_startTime;
                $orderSearch->endtime = $this->_endTime;
                return Application_Model_Order::countorder($orderSearch);
            case Application_Model_GeneralizeRule::Grant_Visiting:
                $visitingSearch = new Application_Model_Filter_VisitingSearch();
                $visitingSearch->userId = $userId;
                $visitingSearch->starttime = $this->_startTime;
                $visitingSearch->endtime = $this->_endTime;
                return Application_Model_VisitingServer::countVisiting($visitingSearch);
            case Application_Model_GeneralizeRule::Grant_Recharge:
                return Application_Model_RechargeBill::countRecharge($userId, Application_Model_PayBill::PAY_STATUS_SUCCESS, $this->_startTime,  $this->_endTime);
            case Application_Model_GeneralizeRule::Grant_Share:
                return 0;
            default:
                return 0;
        }
    }
    /**
     * 发放相对应的礼物
     * @param type $userId 用户Id
     * @param type $ruleVal 礼物对象
     * @param type $receiveId 参与活动的Id
     * @param type $num 参与活动的数量
     * @return type
     */
    private function receiveGift($userId,$ruleVal,$receiveId,$num = 0) {
        $result = 0;
        switch ($ruleVal->giftType) {
            case Application_Model_GeneralizeRule::GiftType_Coupon:
                $giftItem = Application_Model_CouponBatch::load($ruleVal->giftId);
                $result = $this->receiveCoupon($giftItem,$ruleVal, $userId);
                break;
            case Application_Model_GeneralizeRule::GiftType_Store:
                $storeItem = Application_Model_StoreItem::load($ruleVal->giftId);
                $result = $this->receiveStore($storeItem,$ruleVal, $userId);
                break;
            case Application_Model_GeneralizeRule::GiftType_Discount:
                $discount = $ruleVal->GiftName;
                $receiveItem = $this->createdReceive($ruleVal->grantType,$receiveId);
                $result = $this->receiveDiscount($discount,$receiveItem, $ruleVal);
            default:
                break;
        }
        if($result == 1){
            if($ruleVal->ruleLimit == Application_Model_GeneralizeRule::RuleLimit_Num) {
                Application_Model_GeneralizeReceive::addReceive($this->_id, $ruleVal->Id, $userId, $num);
            } else {
                Application_Model_GeneralizeReceive::addReceive($this->_id, $ruleVal->Id, $userId, $receiveId);
            }
        }
        return $result;
    }
    /**
     * 判断是否参与活动 -- 优惠券
     * @param type $giftItem 礼物对象
     * @param type $userId 用户Id
     * @return boolean false 没有 true 参与过
     */
    private function judgeIfUseCoupon($giftItem,$generalizeType,$userId)
    {
        if($generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Participate) {
            return false;
        }
        $couponSearch = new Application_Model_Filter_CouponSearch();
        $couponSearch->userId = $userId;
        $couponSearch->batchNo = $giftItem->No;
        if($generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Day) {
            $couponSearch->dateType = "dateCreated";
            $couponSearch->startTime = date("Y-m-d");
            $couponSearch->endTime = date("Y-m-d");
        }
        $couponItem = Application_Model_Coupon::getCount($couponSearch);
        if($couponItem>0){
            return true;
        }
        return false;
    }
    /**
     * 发放礼物--优惠券
     * @param type $giftItem 礼物对象
     * @param type $ruleVal 发放规则
     * @param type $userId 用户Id
     * @return int
     */
    private function receiveCoupon($giftItem,$ruleVal,$userId)
    {
        if($this->judgeIfUseCoupon($giftItem,$ruleVal->generalizeType, $userId)){
            return 2;
        }
        $countCouponSearch = new Application_Model_Filter_CouponSearch();
        if($ruleVal->generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Day){
            $countCouponSearch->dateType = "dateCreated";
            $countCouponSearch->startTime = date("Y-m-d");
            $countCouponSearch->endTime = date("Y-m-d")." 23:59:59";
        }
        $countCouponSearch->batchNo = $giftItem->no;
        $countCoupon = Application_Model_Coupon::getCount($countCouponSearch);
        if($countCoupon >= $ruleVal->num || $ruleVal->receiveNum >= $ruleVal->num ){
            return 3;
        }
        for ($index = 1; $index <= $ruleVal->ruleNum; $index++) {
            $giftItem->addCouponByBatch($userId);
        }
        $ruleVal->receiveNum = $ruleVal->receiveNum + $ruleVal->ruleNum;
        $ruleVal->save();
        return 1;
    }
    /**
     * 判断是否参与活动 -- 优惠券
     * @param type $giftItem 礼物对象
     * @param type $userId 用户Id
     * @return boolean false 没有 true 参与过
     */
    protected function judgeIfUseStore($giftItem,$generalizeType,$userId)
    {
        if($generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Participate) {
            return false;
        }
        $storeSearch = new Application_Model_Filter_StoreItemSearch();
        $storeSearch->userId = $userId;
        $storeSearch->productName = $giftItem->productName;
        if($generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Day) {
            $storeSearch->dateinbegin = date("Y-m-d");
            $storeSearch->dateInStore = date("Y-m-d");
        }
        $storeItem = Application_Model_StoreItem::getCount($storeSearch);
        if($storeItem > 0){
            return true;
        }
        return false;
    }
    /**
     * 发放礼物--实体礼物
     * @param type $giftItem 礼物对象
     * @param type $ruleVal 发放规则
     * @param type $userId 用户Id
     * @return int
     */
    private function receiveStore($giftItem,$ruleVal,$userId)
    {
        if($this->judgeIfUseStore($giftItem, $ruleVal->generalizeType, $userId)){
            return 2;
        }
        $storeSearch = new Application_Model_Filter_StoreItemSearch();
        $storeSearch->productName = $giftItem->productName;
        if($ruleVal->generalizeType == Application_Model_GeneralizeRule::GeneralizeType_Day){
            $storeSearch->dateinbegin = date("Y-m-d");
            $storeSearch->dateinend = date("Y-m-d")." 23:59:59";
        }
        $countStore = Application_Model_StoreItem::getCount($storeSearch);
        if($countStore >= $ruleVal->num || $ruleVal->receiveNum >= $ruleVal->num ){
            return 3;
        }
        for ($index = 1; $index < $ruleVal->ruleNum; $index++) {
            $giftItem->copyStore($userId);
        }
        $ruleVal->receiveNum = $ruleVal->receiveNum + $ruleVal->ruleNum;
        $ruleVal->save();
        return 1;
    }
    /**
     * 发放礼物--金额折扣
     * @param type $discount 折扣
     * @param type $receiveItem 折扣对象
     * @param type $ruleVal 规则对象
     * @return int
     */
    private function receiveDiscount($discount,$receiveItem, $ruleVal) {
        $receiveItem->addFee(Application_Model_FeeType::ActivityDiscount, $discount);
        $ruleVal->receiveNum = $ruleVal->receiveNum + $ruleVal->ruleNum;
        $ruleVal->save();
        return 1;
    }
    /**
     * 判断该IP是否参与了活动
     * @param type $giftItem 活动对象
     * @param type $userId 用户Id
     * @return boolean true 参与 false 没有
     */
//    private function judgeIfIp($giftItem,$userId)
//    {
//        $userItem = Application_Model_User::load($userId);
//        $userSearch = new Application_Model_Filter_UserSearch();
//        $userSearch->ip = $userItem->Loginip;
//        $userAllItem = Application_Model_User::ByAll($userSearch);
//        foreach ($userAllItem as $userVal) {
//            if($giftItem->Type == Application_Model_GeneralizeGift::Type_Coupon){
//                if($this->judgeIfUseCoupon($giftItem, $userVal->Id)){
//                    return true;
//                }
//            } else if ($giftItem->Type == Application_Model_GeneralizeGift::Type_Store) {
//                if($this->judgeIfUseStore($giftItem, $userVal->Id)){
//                    return true;
//                }
//            }
//        }
//        return false;        
//    }    
}
